import { createRouter, createWebHashHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LayoutIndex from '../views/layout/LayoutIndex.vue';
import LoginIndex from '../views/login/LoginIndex.vue';

const routes = [
  {
    path: '/',
    redirect: { name: 'home' },
  },
  {
    path: '/login',
    name: 'login',
    component: LoginIndex,
  },
  {
    path: '/home',
    name: 'home',
    redirect: { name: 'home-index' },
    component: LayoutIndex,
    children: [
      {
        path: 'index',
        name: 'home-index',
        component: () => import('@/views/home/HomeIndex.vue'),
        meta: {
          needLogin: true,
        },
      },
    ],
  },

  {
    path: '/users',
    name: 'users',
    redirect: { name: 'users-index' },
    component: LayoutIndex,
    children: [
      {
        path: 'index',
        name: 'users-index',
        component: () => import('@/views/users/UsersIndex.vue'),
        meta: {
          needLogin: true,
        },
      },
    ],
  },
  {
    path: '/:other(.*)',
    component: HomeView,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  // 白名单 优先级最高
  if ([].includes(to.name)) {
    return next();
  }
  if (to.meta?.needLogin === true) {
    if (localStorage.token) {
      // 需要登录并已经登录 放行
      return next();
    }
    // 需要登录并未登录 拦截
    return next({ name: 'login' });
  }
  // 其他情况放行
  return next();
});

export default router;
